//
//  Reviewers+Diff.swift
//  GerritHermes
//
//  Created by J.Zhou on 2020/1/20.
//  Copyright © 2020 J.Zhou. All rights reserved.
//

import Foundation

private extension Array where Element == AccountInfo {
    func sorted() -> [AccountInfo] {
        return sorted { (account1, account2) -> Bool in
            account1.accountID < account2.accountID
        }
    }
}

extension ChangeInfo {
    static func diff(old: ChangeInfo, new: ChangeInfo) -> (reviewers: [AccountInfo], cc: [AccountInfo], assignee: AccountInfo?) {
        var reviewers = [AccountInfo]()
        var cc = [AccountInfo]()
        var assignee: AccountInfo?

        let oldReviewers = (old.reviewers?.reviewer ?? []).sorted()
        let newReviewers = (new.reviewers?.reviewer ?? []).sorted()
        let (_, _, addRs) = oldReviewers.split(new: newReviewers) { (o, n) -> Bool in o.accountID == n.accountID }
        reviewers.append(contentsOf: addRs.filter { $0 != new.owner })

        let oldCC = (old.reviewers?.cc ?? []).sorted()
        let newCC = (new.reviewers?.cc ?? []).sorted()
        let (_, _, addCC) = oldCC.split(new: newCC) { (o, n) -> Bool in o.accountID == n.accountID }
        cc.append(contentsOf: addCC.filter { $0 != new.owner })

        if let newAssignee = new.assignee, old.assignee != newAssignee {
            assignee = newAssignee
        }

        return (reviewers, cc, assignee)
    }
}

